package com.br.exemploThreadSala;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ClickApplet extends Applet implements MouseListener {
	boolean clicked;
	int counter;

	public void init() {

		// add a mouse handler to the applet
		addMouseListener(this);

		// add two ClickCanvas components
		add(new ClickCanvas(this));
		add(new ClickCanvas(this));

	}

	// handle mouse clicked event
	public void mouseClicked(MouseEvent e) {
		synchronized (this) {
			clicked = true;
			notifyAll();
		}
		counter++;
		System.out.println("Count: " + counter);
		Thread.currentThread().yield();
		clicked = false;
	}

	// stub methods
	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

} // end of ClickApplet

class ClickCanvas extends Canvas implements Runnable {
	ClickApplet applet;

	ClickCanvas(ClickApplet applet) {
		this.applet = applet;
		setSize(30, 30); // original resize() deprecated
		new Thread(this).start();
	}

	// override run() in Runnable
	public void run() {
		while (true) {
			synchronized (applet) {
				while (!applet.clicked) {
					try {
						applet.wait();
					} catch (InterruptedException e) {
					}
				} // end of while
			} // end of synchronized block
			repaint();

		} // end of while
	} // end of run()

	public void paint(Graphics g) {
		g.drawString(new Integer(applet.counter).toString(), 10, 20);
	}

} // end of ClickCanvas
